<template>
  <div>
    <el-form label-width="200px" >
      <el-button type="primary"  class="title" @click="submitForm">保存</el-button>
    </el-form>

    <mavon-editor
      ref="md"
      @imgAdd="$imgAdd"
      v-model="webDataString"
      :html="true"
      :xssOptions="{
                whiteList: {
                    iframe: ['src', 'height', 'width', 'scrolling','allowfullscreen','frameborder'],
                    div: ['style', 'height', 'width', 'align'],
                    img: ['src', 'height', 'width','style', 'align']
                  }
              }"

    ></mavon-editor>
  </div>

<!--
本地上传请求 http://localhost:9528/api/admin/img/addImg

https://github.com/hinesboy/mavonEditor/blob/2f938f2affd1f4278d35946721a7b7c9251e550b/doc/cn/upload-images.md

仅用作展示可以设置props:
toolbarsFlag: false ,
subfield: false,
defaultOpen: "preview"-->
</template>

<script>
import {homeGet, homeSave} from "@/api/home";
import {imgSave} from "@/api/img";
import {userUpdate} from "@/api/user";

export default {
  data() {
    return{
      webDataString: '',
      homeTitle: ''
    }
  },
  created() {
    homeGet("1").then(
      res=>{
        this.webDataString = res.data.homeHtml
        this.homeTitle=res.data.homeTitle
      }
    )
  },
  methods:{
    $imgAdd(pos,$file){
      /*自定义上传*/

      let formData = new FormData();
      formData.append('file', $file);
      //使用raw才能正常上传

      imgSave(formData).then(
        res=>{
          console.log(res)
          if (res.code===0) {
            this.$message({
              type: 'success',
              message: '上传成功！'
            })
            // 替换文本 res.data.imgLocation
            //
            // 将返回的url替换到文本原位置![...](0) -> ![...](url)
            // $vm.$img2Url 详情见本页末尾
            // 替换文本
            // 将返回的url替换到文本原位置![...](0) -> ![...](url)
            $vm.$img2Url(pos, res.data.imgLocation);

          } else {
            this.$message({
              /*上传失败*/
              type: 'error',
              message: res.msg
            })
          }
        }
      )
    },
    submitForm(){
      const editForm = {
        homeId: '1',
        homeTitle: this.homeTitle,
        homeHtml: this.webDataString,
        homeStatus: '',
      };
      homeSave(editForm).then(res=>{
        if(res.code===0){
          this.$message({
            type: 'success',
            message: res.msg
          })
        }else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    }
  }
};
</script>
